package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.TrackInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.czt.mp3recorder.Mp3Recorder;
import com.czt.mp3recorder.Mp3RecorderUtil;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.DownloadState;
import com.jdy.haoduoai.enums.MediaState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.lyric.LyricAdapter;
import com.jdy.haoduoai.lyric.LyricListener;
import com.jdy.haoduoai.lyric.LyricLoadHelper;
import com.jdy.haoduoai.lyric.LyricSentence;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.FileUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.CustomAnimationDrawableNew;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.jdy.haoduoai.widget.CustomOneBtnDialog;
import com.jdy.haoduoai.widget.progressbar.DonutProgress;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

//import com.tbruyelle.rxpermissions2.RxPermissions;
//
//import io.reactivex.functions.Consumer;


/**
 * 
 * 
 * @author hf
 * 
 */
@SuppressLint({ "HandlerLeak", "Wakelock", "ClickableViewAccessibility" })
public class RecordActivity2 extends BaseActivity implements OnClickListener,
    Callback {

  @InjectView(id = R.id.backbtn, click = true)
  private ImageButton back;

  @InjectView(id = R.id.sv_video)
  private SurfaceView surfaceView;

  @InjectView(id = R.id.shareimg)
  private ImageView shareimg;
  @InjectView(id = R.id.img_djsbg)
  private ImageView img_djsbg;
  @InjectView(id = R.id.img_djsnumber)
  private ImageView img_djsnumber;

  @InjectView(id = R.id.volume_seek)
  private SeekBar seekbarVolume;
  private AudioManager audioMgr = null; // Audio管理器

  @InjectView(id = R.id.download_progress)
  private DonutProgress mDownloadProgress;

  @InjectView(id = R.id.endtime)
  private TextView endtime;

  @InjectView(id = R.id.usetime)
  private TextView usetime;

  @InjectView(id = R.id.toplay)
  private RelativeLayout mTopVideoLayout;

  @InjectView(id = R.id.seek)
  private SeekBar seekbar;

  @InjectView(id = R.id.title)
  private TextView title;

  @InjectView(id = R.id.lyricshow)
  private ListView mLrcListView;

  @InjectView(id = R.id.play, click = true)
  private Button play;

  @InjectView(id = R.id.start, click = true)
  private Button startrecord;

  @InjectView(id = R.id.finish, click = true)
  private Button finish; // 保存

  @InjectView(id = R.id.yuanyin_btn, click = true)
  private ImageView yuanyin_btn;

  @InjectView(id = R.id.record_again, click = true)
  private Button record_again; // 重录

  @InjectView(id = R.id.lyric_pagelabel)
  private TextView lyric_pagelabel;

  public enum RecordState { // 录音状态
    NO_RECORD, RECORDING, RECORD_FINISH
  }

  private DownloadState mDownloadState = DownloadState.None;
  private MediaState mMediaState = MediaState.None;
  private RecordState mRecordState = RecordState.NO_RECORD;

  private ImageLoader mImageLoader;
  private String picurl, name, url, fileurl, lines;

  int id, playtime;
//  private VoiceRecorder mVoiceRecorder;
private Mp3Recorder mRecorder;
  private boolean bHasBgAudio = true;
  private SurfaceHolder surfaceHolder;
  private MediaPlayer mediaPlayer;
  int reslen;
  private URL downloadurl = null;
  private int downloadSize;
  private int fileSize = 0;
  private MediaPlayer mp3Player, notificationPlayer;
  int defvol;
  private WakeLock mWakeLock;

  private Thread mDownloadingThread;
  private boolean trafficWarning;

  private LyricLoadHelper mLyricLoadHelper;

  private LyricAdapter mLyricAdapter;
  private CarlaClassicVo carlaClassicVo;
  private LeUser leUser;

  private AnimationDrawable mAnim;

  private CustomAnimationDrawableNew mCustomAnim;

  private String path;

  private int mPaused = 0;





  private boolean mCountDownAnimationFinished = false;

//  private void askPermission() {
//    new RxPermissions(this)
//            .request(Manifest.permission.RECORD_AUDIO,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
//            .subscribe(new Consumer<Boolean>() {
//              @Override
//              public void accept(Boolean aBoolean) throws Exception {
//                if(aBoolean){
//                  init();
//                }else {
//                  toastShow("权限被拒绝了");
//                  init();
//                }
//              }
//            });
//  }

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recording);
    mWakeLock = Tools.getWakeLock(this, "my Lock");

    hideTitleView();
    initLize();
    initHandler();
    initListener();


    //askPermission();

    mAnim = (AnimationDrawable) img_djsnumber.getDrawable();

    mCustomAnim = new CustomAnimationDrawableNew(mAnim) {

      @Override
      public void onAnimationFinish() {

        img_djsnumber.setVisibility(View.GONE);
        img_djsbg.setVisibility(View.GONE);

        if (mPaused == 0) {
          startToRecord();
        } else {
          startToRecordFromRecover();
        }
        findViewById(R.id.start).setClickable(true);

        mCountDownAnimationFinished = true;
      }
    };

    seekbarVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onProgressChanged(SeekBar seekBar, int progress,
          boolean fromUser) {
        audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, progress / 10,
            AudioManager.FLAG_PLAY_SOUND);

      }
    });
    audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    defvol = audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    seekbarVolume.setProgress(defvol * 10);

    setVideoHeight();

    File mFolder = new File(Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/" + getPackageName());

    if (mFolder.exists()) {
      mFolder.delete();
    }

    if (!mFolder.exists()) {
      mFolder.mkdir();
    }
  }

  private void mute() {
    if (audioMgr == null)
      audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioMgr.setStreamMute(AudioManager.STREAM_MUSIC, true);
  }

  public void unmute() {
    if (audioMgr == null)
      audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioMgr.setStreamMute(AudioManager.STREAM_MUSIC, false);
  }

  private void startToRecord() {
    mRecordState = RecordState.RECORDING;
    startrecord.setBackgroundResource(R.drawable.recordfinish_btn);

    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    surfaceView.setVisibility(View.VISIBLE);
  //  mVoiceRecorder.startRecording(name);
    mRecorder.start();
    mLyricAdapter.startCountDown();
  }

  private void startToRecordFromRecover() {
    mRecordState = RecordState.RECORDING;

    startrecord.setBackgroundResource(R.drawable.recordfinish_btn);

    surfaceView.setVisibility(View.VISIBLE);

    mediaPlayer = new MediaPlayer();
    // surfaceHolder = surfaceView.getHolder();
    fileurl = Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/haoduoai/" + name + ".mp4";

    try {

      mediaPlayer.setDisplay(surfaceHolder);
      mediaPlayer.setDataSource(fileurl);
      mediaPlayer.prepare();
      mTrackInfo = mediaPlayer.getTrackInfo();

      mediaPlayer.start();
      if (mTrackInfo != null && mTrackInfo.length >= 3) {
        TrackInfo info = mTrackInfo[2];
        int trackType = info.getTrackType();
        if (TrackInfo.MEDIA_TRACK_TYPE_AUDIO == trackType) {
          mediaPlayer.selectTrack(2);
        }
      }

      if (mTrackInfo != null && mTrackInfo.length >= 3 && isChildSong) {
        yuanyin_btn.performClick();
      }

      mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {

          startrecord.performClick();
          if (mediaPlayer != null)
            mediaPlayer.setOnCompletionListener(null);
        }
      });

      if (Tools.isNotEmpty(mediaPlayer)) {
        new Thread(new UIUpdateThread()).start();
      }

      //mVoiceRecorder.startRecording(name);

      mRecorder.start();
      mLyricAdapter.startCountDown();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void setVideoHeight() {
    DisplayMetrics metrics = getResources().getDisplayMetrics();

    int w = metrics.widthPixels;

    int h = w * 3 / 4;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, h);

    mTopVideoLayout.setLayoutParams(params);

    RelativeLayout.LayoutParams seekBarParams = (RelativeLayout.LayoutParams) seekbar
        .getLayoutParams();

    seekBarParams.topMargin = h - Tools.getPixelByDip(this, 10);

    seekbar.setLayoutParams(seekBarParams);
  }

  private void initHandler() {
    handler = new Handler() {
      @SuppressWarnings("deprecation")
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (!Thread.currentThread().isInterrupted()) {
          switch (msg.what) {
          case 0:
            mDownloadProgress.setMax(100);
            mDownloadProgress.setVisibility(View.VISIBLE);
            startrecord.setClickable(false);
            shareimg.setAlpha(0);
            mDownloadState = DownloadState.Begin;
            break;
          case 1:
            int currentProgress = (int) (((double) downloadSize / (double) fileSize) * 100);
            mDownloadProgress.setProgress(currentProgress);
            int currentAlpha = (int) ((double) (currentProgress * 255) / (double) 100);
            shareimg.setAlpha(currentAlpha);
            mDownloadState = DownloadState.Downloading;
            // int x=DownedFileLength*100/FileLength;
            // textView.setText(x+"%");
            break;
          case 2:
            mDownloadState = DownloadState.Finished;
            startrecord.setClickable(true);

            toastShow("下载完毕，再次点击【开始】进行配音");
            mDownloadProgress.setVisibility(View.GONE);
            break;
          case 5:
            usetime.setText(DateUtils.getTime(playtime / 1000));
            seekbar.setProgress(playtime / 1000);
            break;
          case 6:
            dismissLoading();
            DateUtils.showToast(getApplicationContext(),
                getString(R.string.push_OK));
            break;
          default:
            break;
          }
        }
      }
    };
  }

  private boolean isChildSong;
  private int mbanner_id;

  private void startCountDownAnimation() {
    findViewById(R.id.start).setClickable(false);

    img_djsnumber.setVisibility(View.VISIBLE);
    img_djsnumber.postDelayed(new Runnable() {
      @Override
      public void run() {
        mAnim.start();
        mCustomAnim.start();
      }
    }, 1000);
  }

  @SuppressWarnings("deprecation")
  private void initLize() {
    yuanyin_btn.bringToFront();

    leUser = LeXiaoXiaoBanApp.getInstance().getUser();
    carlaClassicVo = (CarlaClassicVo) getIntent().getSerializableExtra(
        "carlaclassic");

    mbanner_id = getIntent().getIntExtra("banner_id", -1);

    if (carlaClassicVo.category_id.contains(";11;")) {
      isChildSong = true;
    }

    if (isChildSong) {
      yuanyin_btn.setImageResource(R.drawable.yuanyin_clickable);
    } else {
      yuanyin_btn.setImageResource(R.drawable.yin_clickable);
    }

    // yuanyin_btn.performClick();

    finish.setVisibility(View.INVISIBLE);
    play.setVisibility(View.INVISIBLE);
    record_again.setVisibility(View.INVISIBLE);

    mLyricLoadHelper = new LyricLoadHelper();

    mLyricLoadHelper.setLyricListener(mLyricListener);

    mLyricAdapter = new LyricAdapter(this);

    mLrcListView.setOnTouchListener(new ListView.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
          // Disallow ScrollView to intercept touch events.
          v.getParent().requestDisallowInterceptTouchEvent(true);
          break;

        case MotionEvent.ACTION_UP:
          // Allow ScrollView to intercept touch events.
          v.getParent().requestDisallowInterceptTouchEvent(false);
          break;
        }

        // Handle ListView touch events.
        v.onTouchEvent(event);
        return true;
      }
    });

    mLrcListView.setAdapter(mLyricAdapter);
    mLrcListView.startAnimation(AnimationUtils.loadAnimation(this,
        android.R.anim.fade_in));

    seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

      }

      @Override
      public void onProgressChanged(SeekBar seekBar, int progress,
          boolean fromUser) {
        // TODO Auto-generated method stub

      }
    });

 //   mVoiceRecorder = new VoiceRecorder(new Handler());

    // Intent intent = getIntent();
    id = carlaClassicVo.id;
    picurl = carlaClassicVo.cover;
    name = carlaClassicVo.name;
    url = carlaClassicVo.url;
    lines = carlaClassicVo.lines;
    usetime.setText("0:00");
    reslen = carlaClassicVo.length; // 秒
    endtime.setText("/" + DateUtils.getTime(reslen));
    seekbar.setMax(reslen);
    saveLyric(lines);

    path = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/haoduoai/", "record_" + name + ".mp3").getAbsolutePath();

    initMp3Recorder();

    String lyricPath = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/haoduoai/" + id + ".lrc";
    title.setText(name);
    mLyricLoadHelper.loadLyric(lyricPath);
    mImageLoader = new ImageLoader(this);
    mImageLoader.DisplayImage(picurl, shareimg, false);

    boolean isNoTip = LePreference.getInstance()
        .getBoolean("notipagain", false);

    AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (!localAudioManager.isWiredHeadsetOn() && !isNoTip) {
      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this)
          .setMessageTitle("温馨提示").setMessage("\n使用耳机创作，效果更佳")
          .setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          }).setPositiveButton("不再提醒", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
              LePreference.getInstance().save("notipagain", true);
            }
          });
      CustomCommonDialog cd = cdb.create();
      cd.setCancelable(false);
      cd.setCanceledOnTouchOutside(false);
      cd.show();
    }
  }

  private void initMp3Recorder() {
    Mp3RecorderUtil.init(getApplicationContext(), true);


    int maxSec = 180; // 3mins

    if (reslen > 0) {
      maxSec = reslen + 120;
    }

    mRecorder = new Mp3Recorder();
    mRecorder.setOutputFile(path)
            .setMaxDuration(maxSec)// 3mins
            .setCallback(new Mp3Recorder.Callback() {
                           /* @Override
                            public void onRecording(double duration) {
                                tvProgress.setText( String.format("%d分%d秒",(int)(duration/1000/60),(int)(duration/1000%60))+"---"+duration );
                            }*/

              @Override
              public void onRecording(double duration, double volume) {
                String str = "";
                str = String.format("duration:\n"+"%d分%d秒",(int)(duration/1000/60),(int)(duration/1000%60))+"---"+duration+"\n"
                        + "分贝值:\n"+volume;
              //  tvProgress.setText(str);

              }

              @Override
              public void onStart() {
           //     toast("开始了....");

              }

              @Override
              public void onPause() {
              //  toast("暂停了....");
              }

              @Override
              public void onResume() {
               // toast("恢复....");
              }

              @Override
              public void onStop(int action) {
              //  toast("onStop....");
              //  tvProgress.setText("onStop");
              }

              @Override
              public void onReset() {
              //  toast("onReset....");
             //   tvProgress.setText("onReset");
              }

              @Override
              public void onMaxDurationReached() {
             //   toast("onMaxDurationReached....");
             //   tvProgress.setText("onMaxDurationReached");

                if (mRecordState == RecordState.RECORDING) {
                  if (mRecorder.getRecorderState() == Mp3Recorder.State.RECORDING
                          || mRecorder.getRecorderState() == Mp3Recorder.State.STOPPED) {
                    mRecordState = RecordState.RECORD_FINISH;

                    if (mediaPlayer != null) {
                      mediaPlayer.stop();
                      mediaPlayer.release();
                      mediaPlayer = null;
                    }

                    if (mLyricAdapter != null)
                      mLyricAdapter.abortCountDown();

                    // mVoiceRecorder.stopRecoding();
                    mRecorder.stop(Mp3Recorder.ACTION_STOP_ONLY);
                    play.setClickable(true);
                    play.setVisibility(View.VISIBLE);
                    // play.setBackgroundResource(R.drawable.played);
                    finish.setClickable(true);
                    finish.setVisibility(View.VISIBLE);
                    play.setVisibility(View.VISIBLE);
                    yuanyin_btn.setClickable(false);
                    record_again.setVisibility(View.VISIBLE);
                  }
                }
              }
            });

    //mRecorder.start();
  }

  // Handler test = new Handler() {
  // };

  private void initListener() {
    play.setClickable(false);
    play.setVisibility(View.INVISIBLE);

    yuanyin_btn.setClickable(true);

    finish.setClickable(false);
    finish.setVisibility(View.INVISIBLE);
    record_again.setVisibility(View.INVISIBLE);
  }

  private long remainTime;

  private final LyricListener mLyricListener = new LyricListener() {

    @Override
    public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
      // Log.i(TAG, "onLyricLoaded");
      if (lyricSentences != null) {
        // Log.i(TAG, "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
        // + ",当前句子索引=" + index);

        if (lyricSentences != null && lyricSentences.size() > 1) {
          long line1 = lyricSentences.get(1).getStartTime();
          remainTime = line1; // (line1 - 3 * 1000);

          if (remainTime < 0) {
            remainTime = 0;
          }
        }

        mLyricAdapter.setLyric(lyricSentences);
        mLyricAdapter.setCurrentSentenceIndex(index);
        mLyricAdapter.notifyDataSetChanged();
        // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
        // mHandler.sendMessageDelayed(
        // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
        // 100);
      }
    }

    @Override
    public void onLyricSentenceChanged(final int indexOfCurSentence) {
      // Log.i(TAG, "onLyricSentenceChanged--->当前句子索引=" +
      // indexOfCurSentence);
      runOnUiThread(new Runnable() {

        @Override
        public void run() {

          mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
          mLyricAdapter.notifyDataSetChanged();
          mLrcListView.smoothScrollToPositionFromTop(indexOfCurSentence,
              mLrcListView.getHeight() / 2, 500);
        }
      });

    }
  };

  @Override
  public void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    if (mWakeLock != null)
      mWakeLock.acquire();
    if (mLyricAdapter != null) {
      mLyricAdapter.resumeCountDown();
    }

    if (mPaused != 0 && !mCountDownAnimationFinished) {

      String filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/" + name + ".mp4";

      File file = new File(filePath);
      if (file.exists()) {
        showToastLong(this, "请点击开始录音!");
      }

      initLize();

      seekbar.setProgress(0);
      // surfaceView.setVisibility(View.GONE);
      startrecord.setBackgroundResource(R.drawable.startrecord_btn);

      play.setVisibility(View.INVISIBLE);
      finish.setVisibility(View.INVISIBLE);
      play.setVisibility(View.INVISIBLE);
      yuanyin_btn.setClickable(true);
      record_again.setVisibility(View.INVISIBLE);
      mRecordState = RecordState.NO_RECORD;
      findViewById(R.id.start).setClickable(true);
    }
    mCountDownAnimationFinished = false;
  }

  @Override
  public void onPause() {
    mPaused++;
    super.onPause();

    MobclickAgent.onPause(this);

    if (mWakeLock != null)
      mWakeLock.release();
    if (mDownloadState.equals(DownloadState.Begin)
        || mDownloadState.equals(DownloadState.Downloading)) {
      mDownloadingThread.interrupt();
      String filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/" + name + ".mp4";
      File file = new File(filePath);
      if (file.exists()) {
        file.delete();
      }
    }

    if (mRecordState == RecordState.RECORDING) {
      mRecordState = RecordState.RECORD_FINISH;
      if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
      }

//      if (mVoiceRecorder.isRecording()) {
//        mVoiceRecorder.stopRecoding();
//      }

      if (mRecorder.getRecorderState() == Mp3Recorder.State.RECORDING) {
        mRecorder.stop(Mp3Recorder.ACTION_STOP_ONLY);
      }
    }

    if (mAnim != null) {
      mAnim.stop();
      // mAnim.selectDrawable(0);
    }
    if (mCustomAnim != null) {
      mCustomAnim.stop();
      // mCustomAnim.selectDrawable(0);
    }

    if (mLyricAdapter != null)
      mLyricAdapter.abortCountDown();

    if (notificationPlayer != null) {
      notificationPlayer.stop();
      notificationPlayer.release();
      notificationPlayer = null;
    }

    img_djsnumber.setVisibility(View.GONE);
    img_djsbg.setVisibility(View.GONE);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.yuanyin_btn:
      if (mediaPlayer != null) {
        TrackInfo[] trackInfos = mediaPlayer.getTrackInfo();
        int tracks = trackInfos.length;
        if (bHasBgAudio) {
          // 去掉原声留背景音
          if (tracks >= 3) {
            TrackInfo info = trackInfos[2];
            int trackType = info.getTrackType();
            if (TrackInfo.MEDIA_TRACK_TYPE_AUDIO == trackType) {
              mediaPlayer.selectTrack(2);
            }
          } else {
            mute();
          }
          bHasBgAudio = false;

          if (isChildSong) {
            yuanyin_btn.setImageResource(R.drawable.yuanyin_notclickable);
          } else {
            yuanyin_btn.setImageResource(R.drawable.yin_notclickable);
          }

        } else {
          // 原声+背景音
          mediaPlayer.selectTrack(1);
          bHasBgAudio = true;
          if (tracks < 3) {
            unmute();
          }
          if (isChildSong) {
            yuanyin_btn.setImageResource(R.drawable.yuanyin_clickable);
          } else {
            yuanyin_btn.setImageResource(R.drawable.yin_clickable);
          }

        }
      }
      break;
    case R.id.record_again:
      initLize();
      // usetime.setText("0:00");
      // endtime.setText("/" + DateUtils.getTime(reslen));
      // seekbar.setMax(reslen);
      seekbar.setProgress(0);
      surfaceView.setVisibility(View.GONE);
      startrecord.setBackgroundResource(R.drawable.startrecord_btn);

      play.setVisibility(View.INVISIBLE);
      finish.setVisibility(View.INVISIBLE);
      play.setVisibility(View.INVISIBLE);
      yuanyin_btn.setClickable(true);
      record_again.setVisibility(View.INVISIBLE);
      mRecordState = RecordState.NO_RECORD;
      mAnim.stop();
      mCustomAnim.stop();
      mAnim.selectDrawable(0);
      mCustomAnim.selectDrawable(0);
      break;
    case R.id.backbtn:
      finish();
      break;
    case R.id.start:
      String filePath = Environment.getExternalStorageDirectory()
          + "/haoduoai/" + name + ".mp4";

      File file = new File(filePath);
      if (!file.exists()) {
        if (Tools.ExistSDCard() && Tools.getSDFreeSize() < 200) {
          CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(this)
              .setMessage("手机剩余空间不够，请清理后再试！").setPositiveButton("确定",
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      dialog.dismiss();
                    }
                  });
          CustomOneBtnDialog cd = cdb.create();
          cd.setCancelable(false);
          cd.setCanceledOnTouchOutside(false);
          cd.show();
        } else {
          CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
              RecordActivity2.this).setTitle("提示")
              .setMessage("还没下载该故事，是否现在开始下载？")
              .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                  dialog.dismiss();
                }
              }).setPositiveButton("下载", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();

                  if (!trafficWarning
                      && !Tools.isWifiConnected(RecordActivity2.this)
                      && handler != null) {
                    trafficWarning = true;
                    handler.post(new Runnable() {

                      @Override
                      public void run() {
                        if (isFinishing()) {
                          return;
                        }

                        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                            RecordActivity2.this)
                            .setTitle("温馨提示")
                            .setMessage("您当前使用移动网络，继续下载将产生流量费用，敬请留意")
                            .setNegativeButton("继续下载",
                                new DialogInterface.OnClickListener() {
                                  @Override
                                  public void onClick(DialogInterface dialog,
                                      int which) {
                                    mDownloadingThread = new Thread() {
                                      @Override
                                      public void run() {
                                        try {
                                          downloadFile(url, "haoduoai/",
                                              name + ".mp4");
                                        } catch (IOException e) {
                                          e.printStackTrace();
                                        }
                                      }
                                    };
                                    mDownloadingThread.start();
                                    dialog.dismiss();
                                  }
                                })
                            .setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {
                                  @Override
                                  public void onClick(DialogInterface dialog,
                                      int which) {
                                    trafficWarning = false;
                                    dialog.dismiss();
                                  }
                                });

                        if (!isFinishing()) {
                          cdb.create().show();
                        }
                      }
                    });
                  } else {
                    mDownloadingThread = new Thread() {
                      @Override
                      public void run() {
                        try {
                          downloadFile(Tools.replaceBlank(url), "haoduoai/",
                              name + ".mp4");
                        } catch (IOException e) {
                          e.printStackTrace();
                        }
                      }
                    };
                    mDownloadingThread.start();
                    dialog.dismiss();
                  }

                }
              });

          if (!isFinishing()) {
            cdb.create().show();
          }
        }
      } else {
        if (mRecordState == RecordState.NO_RECORD) {

          img_djsnumber.setVisibility(View.VISIBLE);
          img_djsbg.setVisibility(View.VISIBLE);

          notificationPlayer = MediaPlayer.create(this, R.raw.luyin_tips);
          notificationPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
          notificationPlayer.start();

          startCountDownAnimation();

        } else if (mRecordState == RecordState.RECORDING) {
          if (mRecorder.getRecorderState() == Mp3Recorder.State.RECORDING) {
            mRecordState = RecordState.RECORD_FINISH;

            if (mediaPlayer != null) {
              mediaPlayer.stop();
              mediaPlayer.release();
              mediaPlayer = null;
            }

            if (mLyricAdapter != null)
              mLyricAdapter.abortCountDown();

           // mVoiceRecorder.stopRecoding();
            mRecorder.stop(Mp3Recorder.ACTION_STOP_ONLY);
            play.setClickable(true);
            play.setVisibility(View.VISIBLE);
            // play.setBackgroundResource(R.drawable.played);
            finish.setClickable(true);
            finish.setVisibility(View.VISIBLE);
            play.setVisibility(View.VISIBLE);
            yuanyin_btn.setClickable(false);
            record_again.setVisibility(View.VISIBLE);
          }
        }
      }
      break;
    case R.id.play: // 预览
      if (mMediaState.equals(MediaState.None)
          || mMediaState.equals(MediaState.Playing)
          || mMediaState.equals(MediaState.Pause)) {
        // play.setBackgroundResource(R.drawable.pauserecord);
        mMediaState = MediaState.Playing;
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
          mediaPlayer.stop();
          mediaPlayer.release();
          mediaPlayer = null;
        }

        if (mp3Player != null && mp3Player.isPlaying()) {
          mp3Player.stop();
          mp3Player.release();
          mp3Player = null;
        }

        mediaPlayer = new MediaPlayer();
        mp3Player = new MediaPlayer();
        mediaPlayer.setDisplay(surfaceHolder);
        try {
          mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()
              .getAbsolutePath() + "/haoduoai/" + name + ".mp4");
          mediaPlayer.prepare();

          mediaPlayer.setVolume(0.0f, 0.0f);

          mediaPlayer.start();

          TrackInfo[] trackInfos = mediaPlayer.getTrackInfo();
          int tracks = trackInfos.length;
          if (tracks >= 3) {
            TrackInfo info = trackInfos[2];
            int trackType = info.getTrackType();
            if (TrackInfo.MEDIA_TRACK_TYPE_AUDIO == trackType) {
              mediaPlayer.selectTrack(2);
            }
          }

          mp3Player.setDataSource(/*mVoiceRecorder.getVoiceFileName()*/path);
          mp3Player.prepare();
          mp3Player.start();
          new Thread(new UIUpdateThread()).start();
        } catch (IllegalArgumentException e) {
          e.printStackTrace();
        } catch (SecurityException e) {
          e.printStackTrace();
        } catch (IllegalStateException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }/*
        * else if (mMediaState.equals(MediaState.Playing)) { //
        * play.setBackgroundResource(R.drawable.played); mMediaState =
        * MediaState.Pause;
        * 
        * if (mp3Player != null) { mp3Player.pause(); }
        * 
        * if (mediaPlayer != null) { mediaPlayer.pause(); }
        * 
        * } else if (mMediaState.equals(MediaState.Pause)) { //
        * play.setBackgroundResource(R.drawable.pauserecord); mMediaState =
        * MediaState.Playing; if (mp3Player != null) { mp3Player.start(); }
        * 
        * if (mediaPlayer != null) { mediaPlayer.start(); }
        * 
        * new Thread(new UIUpdateThread()).start(); }
        */
      break;
    case R.id.finish:// 提交
      // 上传配音
      System.out.println("=======record====pushOK====");

      showloading("");
      uploadAudioFile(/*mVoiceRecorder.getVoiceFileName()*/path);

      // mixAudioVedio();

      // play.setVisibility(View.INVISIBLE);
      // usetime.setText("0:00");
      // endtime.setText("/" + DateUtils.getTime(reslen));
      // seekbar.setMax(reslen);
      // seekbar.setProgress(0);
      // surfaceView.setVisibility(View.GONE);
      // startrecord.setBackgroundResource(R.drawable.startrecord_btn);
      // finish.setVisibility(View.INVISIBLE);
      // record_again.setVisibility(View.INVISIBLE);
      //
      // mRecordState = RecordState.NO_RECORD;
      break;
    default:
      break;
    }
  }

//  @SuppressWarnings("unused")
//  private void mixAudioVedio() {
//    final String pathBase = Environment.getExternalStorageDirectory()
//        .getAbsolutePath() + "/" + getPackageName();
//
//    File fMP4 = new File(pathBase + "/mixfinalvideo.mp4");
//    if (fMP4.exists()) {
//      fMP4.delete();
//    }
//
//    new Thread() {
//      @Override
//      public void run() {
//
//        try {
//          String audioEnglish = mVoiceRecorder.getVoiceFileName();
//          String video = Environment.getExternalStorageDirectory()
//              .getAbsolutePath() + "/haoduoai/" + name + ".mp4";
//
//          Movie countVideo = MovieCreator.build(video);
//          Movie countAudioEnglish = MovieCreator.build(audioEnglish);
//
//          Track audioTrackEnglish = countAudioEnglish.getTracks().get(0);
//
//          if (countVideo.getTracks().size() <= 1) {
//            countVideo.addTrack(audioTrackEnglish);
//          } else {
//            countVideo.getTracks().add(1, audioTrackEnglish);
//          }
//
//          {
//            Container out = new DefaultMp4Builder().build(countVideo);
//            FileOutputStream fos = new FileOutputStream(new File(pathBase
//                + "/mixfinalvideo.mp4"));
//            out.writeContainer(fos.getChannel());
//            fos.close();
//          }
//
//          // 1 step
//          uploadAudioFile(mVoiceRecorder.getVoiceFileName());
//        } catch (Exception e) {
//          runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//              dismissLoading();
//            }
//          });
//        }
//
//      };
//    }.start();
//  }

  @SuppressWarnings({ "resource", "deprecation" })
  public int downloadFile(String urlStr, String path, String fileName)
      throws IOException {
    downloadurl = new URL(URLEncoder.encode(urlStr).replace("%3A", ":")
        .replace("%2F", "/"));

    HttpURLConnection urlconn = (HttpURLConnection) downloadurl
        .openConnection();
    InputStream inputstream = urlconn.getInputStream();
    OutputStream outputStream = null;
    try {
      FileUtils fileutils = new FileUtils();
      if (fileutils.isFileExist(path + fileName)) {
        return 1;
      } else {

        if (!fileutils.isFileExist(path)) {
          fileutils.createSDDir(path);
        }
        File file = fileutils.createSDFile(path + fileName);
        outputStream = new FileOutputStream(file);
        this.fileSize = urlconn.getContentLength();
        handler.sendEmptyMessage(0);
        byte buffer[] = new byte[4 * 1024];
        int temp = 0;
        downloadSize = 0;
        while ((temp = inputstream.read(buffer)) != -1) {
          outputStream.write(buffer, 0, temp);
          downloadSize += temp;
          System.out.println("=======downloadSize=====" + downloadSize);
          handler.sendEmptyMessage(1);
        }

        outputStream.flush();
        handler.sendEmptyMessage(2);
        if (file == null)
          return -1;
        inputstream.close();
        outputStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return -1;
    }
    return 0;
  }

  @Override
  public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
  }

  private TrackInfo[] mTrackInfo;

  @Override
  public void surfaceCreated(SurfaceHolder arg0) {
    if (mPaused == 0) {

      new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
          mediaPlayer = new MediaPlayer();
          mediaPlayer.setDisplay(surfaceHolder);
          fileurl = Environment.getExternalStorageDirectory().getAbsolutePath()
              + "/haoduoai/" + name + ".mp4";

          try {
            mediaPlayer.setDataSource(fileurl);
            mediaPlayer.prepare();
            mTrackInfo = mediaPlayer.getTrackInfo();

            // if (mTrackInfo != null && mTrackInfo.length < 3) {
            // runOnUiThread(new Runnable() {
            // @Override
            // public void run() {
            // yuanyin_btn.setClickable(false);
            // yuanyin_btn.setEnabled(false);
            // }
            // });
            // }

            // bgmediaPlayer.getTrackInfo();

            mediaPlayer.start();
            int tracks = mTrackInfo.length;
            if (tracks >= 3) {
              TrackInfo info = mTrackInfo[2];
              int trackType = info.getTrackType();
              if (TrackInfo.MEDIA_TRACK_TYPE_AUDIO == trackType) {
                mediaPlayer.selectTrack(2);
              }
            }

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

              @Override
              public void onCompletion(MediaPlayer mp) {

                startrecord.performClick();
                if (mediaPlayer != null)
                  mediaPlayer.setOnCompletionListener(null);
              }
            });

          } catch (Exception e) {
            e.printStackTrace();
          }
          return null;
        }

        @Override
        protected void onPostExecute(Void result) {
          if (Tools.isNotEmpty(mediaPlayer)) {
            seekbar.setMax(mediaPlayer.getDuration() / 1000);
            endtime.setText(" / "
                + DateUtils.getTime(mediaPlayer.getDuration() / 1000));
            new Thread(new UIUpdateThread()).start();
          }
          if (mTrackInfo.length >= 3) {
            yuanyin_btn.performClick();
          }
        }

      }.execute((Void[]) null);
    } else {

      showToastLong(this, "请点击开始录音!");
      initLize();
      // usetime.setText("0:00");
      // endtime.setText("/" + DateUtils.getTime(reslen));
      // seekbar.setMax(reslen);
      seekbar.setProgress(0);
      // surfaceView.setVisibility(View.GONE);
      startrecord.setBackgroundResource(R.drawable.startrecord_btn);

      play.setVisibility(View.INVISIBLE);
      finish.setVisibility(View.INVISIBLE);
      play.setVisibility(View.INVISIBLE);
      yuanyin_btn.setClickable(true);
      record_again.setVisibility(View.INVISIBLE);
      mRecordState = RecordState.NO_RECORD;
      // mAnim.stop();
      // mCustomAnim.stop();
      // mAnim.selectDrawable(0);
      // mCustomAnim.selectDrawable(0);
    }

  }

  @Override
  public void surfaceDestroyed(SurfaceHolder arg0) {
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    if (mp3Player != null && mp3Player.isPlaying()) {
      mp3Player.stop();
    }
  }

  public void saveLyric(String text) {
    FileOutputStream fos = null;
    File file = new File(Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/haoduoai/" + id + ".lrc");
    try {
      fos = new FileOutputStream(file);
      try {
        JSONArray ja = new JSONArray(text);
        for (int i = 0; i < ja.length(); i++) {
          JSONObject jo = ja.getJSONObject(i);
          if (jo.has("time")) {
            fos.write((jo.getString("time") + jo.getString("cont") + "\n")
                .getBytes());
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
      // fos.write(text.getBytes());
      fos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private class UIUpdateThread implements Runnable {
    long time = 500; // 滚动速度

    @Override
    public void run() {
      while (mediaPlayer != null) {
        try {
          if (mediaPlayer.isPlaying()) {
            playtime = mediaPlayer.getCurrentPosition();
            mLyricLoadHelper.notifyTime(playtime);
            handler.sendEmptyMessage(5);
            try {
              Thread.sleep(time);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        } catch (IllegalStateException e) {
          mediaPlayer = null;
        }
      }
    }
  }

  private String mp3PathPost = "", mp4PathPost = "";

  private void uploadAudioFile(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          mp3PathPost = result.data;
          // String pathBase = Environment.getExternalStorageDirectory()
          // .getAbsolutePath() + "/" + getPackageName();
          // uploadVedioFile(pathBase + "/mixfinalvideo.mp4");
          submitDubStory();
        } else {
          dismissLoading();
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MOBILE_I, leUser.id);
        param_.put(HttpUtils.TAG_MODULE_I, "dub/story");
        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
            HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

//  private void uploadVedioFile(final String filePath) {
//    new CustomAsyncTask(this, new IAsyncTask() {
//      @Override
//      public void onRecieveData(Activity activity, ResponseResult result) {
//        if (result.isSuccess()) {
//          mp4PathPost = result.data;
//          submitDubStory();
//        } else {
//          dismissLoading();
//          toastShow(result.data);
//        }
//      }
//
//      @Override
//      public ResponseResult doInbackground(Activity activity) {
//
//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//        param_.put(HttpUtils.TAG_MOBILE_I, leUser.id);
//        param_.put(HttpUtils.TAG_MODULE_I, "dub/story");
//        return HttpUtils.startUploadRequest(HttpUtils.API_URL
//            + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
//            HttpUtils.TAG_POST_REQUEST);
//
//      }
//    }).execute("请检查网络连接!");
//  }

  private void submitDubStory() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();
        if (result.isSuccess()) {
          toastShow("上传成功");

          int localId = 0;
          try {
            localId = Integer.parseInt(result.data);
          } catch (NumberFormatException e) {
            e.printStackTrace();
          }

          Intent py_bf = new Intent();
          py_bf.putExtra("name", name);
          py_bf.putExtra("pic2", picurl);
          py_bf.putExtra("id", localId);
          py_bf.putExtra("share_data", "配音故事");
          py_bf.putExtra("reslen", reslen);
          py_bf.putExtra("banner_id", mbanner_id);

          String audioEnglish = path;/*mVoiceRecorder.getVoiceFileName();*/
          String video = Environment.getExternalStorageDirectory()
              .getAbsolutePath() + "/haoduoai/" + name + ".mp4";

          py_bf.putExtra("mix_audiopath", audioEnglish);
          py_bf.putExtra("mix_videopath", video);

          py_bf.putExtra("entity_id", id);

          py_bf.putExtra("mp3PathPost", mp3PathPost);

          py_bf.setClass(RecordActivity2.this, StoryDubPlayActivity.class);
          startActivity(py_bf);
          // finish();
        } else {
          dismissLoading();
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
        param_.put("entity_id", id);
        param_.put("av", mp3PathPost);
        if (Tools.isNotEmpty(mp4PathPost)) {
          param_.put("merge_av", mp4PathPost);
        }
        param_.put("catalog", "story");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils
            .startRequest(HttpUtils.API_URL + HttpUtils.GET_DUBS_METHOD_GET,
                param_, HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    mRecorder.stop(Mp3Recorder.ACTION_STOP_ONLY);

    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.release();
      mediaPlayer = null;
    }
    if (mp3Player != null) {
      mp3Player.stop();
      mp3Player.release();
      mp3Player = null;
    }

    if (notificationPlayer != null) {
      notificationPlayer.stop();
      notificationPlayer.release();
      notificationPlayer = null;
    }
  }

}
